package com.jy.app.lib.view.uilistview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewTreeObserver;

import com.jy.app.lib.application.BaseApplication;

/**
 * Created by 15014 on 2017/5/3.
 */

public class PercentHeaderView extends View {
    private final int MAX_PROGRESS = 100;//最大进度
    private final int MAX_ANGLE = 360; //最大角度
    private final int MAX_ALPHA = 255;//最大透明度
    private final int ROTATE_SPEED = 7;//旋转速度
    private final int VIEW_REFRESH = 20;//界面刷新时间
    private final int MAX_RIGHT_ANGLE = 20; //对号旋转最大角度

    private float circular_size = 25;  //圆直径
    private int good_rotate = 70;   //进度达到70时旋转完成
    private int color = Color.rgb(56, 163, 235);
    private int progress = 0; //进度
    private boolean isRotate = false; // 是否旋转
    private boolean isComplete = false;  //是否完成
    private Paint paint;
    private Paint paintArrow;
    private Paint paintArrow1;
    private Paint paintWrite;
    private Paint paintRight;

    private int VIEW_WIDE, VIEW_HEIGHT;// 声明控件宽高
    private String text = "下拉重新加载";

    private float Y;  //中心点Y坐标

    private int angle = 0;  //当前旋转角度

    private int rightAngle = MAX_RIGHT_ANGLE; //当前对号角度

    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            invalidate();
        }
    };

    public PercentHeaderView(Context context) {
        super(context);
    }

    public PercentHeaderView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    //初始化
    private void init() {
        try {
            int colorId = getResources().getIdentifier("uilist",
                    "color", BaseApplication.appContext.getPackageName());
            color = getResources().getColor(colorId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        getCoreLocation();
        setPaint();
        circular_size = dip2px(circular_size);
    }

    /**
     * 设置显示文字
     *
     * @param text 文字
     */
    public void setText(String text) {
        this.text = text;
        postInvalidate();
    }

    /**
     * 设置进度
     *
     * @param progress 进度
     */
    public void setProgress(int progress) {
        this.progress = progress > MAX_PROGRESS ? MAX_PROGRESS : progress < 0 ? 0 : progress;
        invalidate();
    }

    /**
     * 设置是否开始旋转
     *
     * @param isRotate 当进度达到MAX时才开始旋转
     */
    public void setRotate(boolean isRotate) {
        this.isRotate = isRotate;
        invalidate();
    }

    /**
     * 是否完成
     *
     * @param isComplete
     */
    public void setComplete(boolean isComplete) {
        this.isComplete = isComplete;
        invalidate();
    }

    /**
     * 恢复初始状态
     */
    public void recovery() {
        progress = 0;
        isRotate = false;
        isComplete = false;
        rightAngle = MAX_RIGHT_ANGLE;
        invalidate();
    }

    /**
     * 设置画笔
     */
    private void setPaint() {
        paint = new Paint();
        paint.setAntiAlias(true); //打开抗锯齿
        paint.setDither(true);  ////设置是否抖动
        paint.setColor(color);

        paintArrow = new Paint();
        paintArrow.setAntiAlias(true); //打开抗锯齿
        paintArrow.setDither(true);  ////设置是否抖动
        paintArrow.setStyle(Paint.Style.STROKE); //设置空心
        paintArrow.setStrokeWidth(dip2px(1.5)); //设置画笔宽度
        paintArrow.setColor(Color.WHITE);

        paintArrow1 = new Paint();
        paintArrow1.setAntiAlias(true); //打开抗锯齿
        paintArrow1.setDither(true);  ////设置是否抖动
        paintArrow1.setColor(Color.WHITE);

        paintWrite = new Paint(Paint.ANTI_ALIAS_FLAG);
        paintWrite.setStrokeWidth(3);
        paintWrite.setTextSize(dip2px(10));
        paintWrite.setColor(Color.BLACK);

        paintRight = new Paint();
        paintRight.setAntiAlias(true); //打开抗锯齿
        paintRight.setDither(true);  ////设置是否抖动
        paintRight.setStyle(Paint.Style.STROKE); //设置空心
        paintRight.setStrokeWidth(dip2px(2)); //设置画笔宽度
        paintRight.setColor(Color.WHITE);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        drawing(canvas);
        write(canvas);
        super.onDraw(canvas);

    }

    /**
     * 绘制背景圆
     */
    private void drawing(Canvas canvas) {
        //计算图形中点Y坐标
        Y = (VIEW_HEIGHT / 2) - (dip2px(6) / MAX_PROGRESS * progress);
        Y += ((Y + (circular_size) / 2) - (((Y + (circular_size) / 2) / MAX_PROGRESS) * progress));

        paint.setAlpha((int) (isComplete ? MAX_ALPHA : (MAX_ALPHA / MAX_PROGRESS) * progress));  //设置透明度
        //固定背景圆位置
        RectF oval = new RectF();
        oval.top = Y - (circular_size / 2);
        oval.left = (VIEW_WIDE - circular_size) / 2;
        ;
        oval.right = oval.left + circular_size;
        oval.bottom = oval.top + circular_size;
        //画圆
        canvas.drawArc(oval, -90, isComplete ? MAX_ANGLE : ((MAX_ANGLE / good_rotate) * progress), true, paint);

        if (progress > good_rotate && !isComplete) {  //当未完成且背景圆画好后开始画内圆
            withinCircular(oval, canvas);
        }
        if (!isComplete && isRotate && progress >= MAX_PROGRESS) {
            if (angle > MAX_ANGLE) angle -= MAX_ANGLE;
            angle += ROTATE_SPEED;
            handler.postDelayed(runnable, VIEW_REFRESH);
        } else {
            angle = 0;
        }
        if (isComplete && progress >= MAX_PROGRESS) {
            right(canvas);
            if (rightAngle > 0) {
                rightAngle-=2;
                handler.postDelayed(runnable, VIEW_REFRESH);
            }
        }
    }

    /**
     * 绘制内圆
     */
    private void withinCircular(RectF oval, Canvas canvas) {
        paintArrow.setAlpha((int) ((progress - good_rotate) * (MAX_ALPHA / (MAX_PROGRESS - good_rotate))));//设置内圆透明度
        oval.top = Y - (circular_size / 2) + circular_size / 4;
        oval.bottom = oval.top + circular_size - circular_size / 4 * 2;

        oval.left = (VIEW_WIDE - circular_size) / 2 + circular_size / 4;
        ;
        oval.right = oval.left + circular_size - circular_size / 4 * 2;
        canvas.drawArc(oval, angle + (int) ((progress - good_rotate) * (90 / (MAX_PROGRESS - good_rotate))), 270, false, paintArrow);
        if (!isRotate) {
            Arrow(canvas);
        }
    }

    /**
     * 绘制箭头
     */
    private void Arrow(Canvas canvas) {
        paintArrow.setAlpha((int) ((progress - good_rotate) * (MAX_ALPHA / (MAX_PROGRESS - good_rotate))));//设置箭头透明度
        Path path = new Path();
        float Y1 = Y - (circular_size / 2) + circular_size / 4; //计算箭头底部2点Y坐标
        int arrowAngle = -(int) ((progress - good_rotate) * (90 / (MAX_PROGRESS - good_rotate))); //计算目前旋转角度
        //开始绘画
        Float[] f1 = calculationCoordinate(VIEW_WIDE / 2 + dip2px(2), Y1+dip2px(0.2) , VIEW_WIDE / 2, Y, arrowAngle);
        path.moveTo(f1[0], f1[1]);
        Float[] f2 = calculationCoordinate(VIEW_WIDE / 2, Y1 - dip2px(1.6), VIEW_WIDE / 2, Y, arrowAngle);
        path.lineTo(f2[0], f2[1]);
        Float[] f3 = calculationCoordinate(VIEW_WIDE / 2, Y1 + dip2px(1.8), VIEW_WIDE / 2, Y, arrowAngle);
        path.lineTo(f3[0], f3[1]);
        path.close();
        canvas.drawPath(path, paintArrow1);
    }

    /**
     * 绘制文字
     */
    private void write(Canvas canvas) {
        Paint.FontMetricsInt fontMetrics = paintWrite.getFontMetricsInt();
        float baseline = Y - fontMetrics.bottom - fontMetrics.top + circular_size / 5 * 4;
        // 下面这行是实现水平居中，drawText对应改为传入targetRect.centerX()
        paintWrite.setTextAlign(Paint.Align.CENTER);
        canvas.drawText(text, VIEW_WIDE / 2, baseline, paintWrite);
    }

    /**
     * 画对号
     */
    private void right(Canvas canvas) {
        paintRight.setAlpha(MAX_ALPHA);
        Path path = new Path();
        Float[] f1 = calculationCoordinate(VIEW_WIDE / 2 - (circular_size / 5), Y, VIEW_WIDE / 2, Y, rightAngle);
        path.moveTo(f1[0], f1[1]);
        Float[] f2 = calculationCoordinate(VIEW_WIDE / 2, Y + (circular_size / 6), VIEW_WIDE / 2, Y, rightAngle);
        path.lineTo(f2[0], f2[1]);
        Float[] f3 = calculationCoordinate(VIEW_WIDE / 2 + (circular_size / 4), Y - (circular_size / 6), VIEW_WIDE / 2, Y, rightAngle);
        path.lineTo(f3[0], f3[1]);
        canvas.drawPath(path, paintRight);
    }


    /**
     * 获取控件宽高
     */
    private void getCoreLocation() {
        ViewTreeObserver vto = getViewTreeObserver();
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            public boolean onPreDraw() {
                getViewTreeObserver().removeOnPreDrawListener(this);
                VIEW_HEIGHT = getMeasuredHeight();
                VIEW_WIDE = getMeasuredWidth();
                return true;
            }
        });
    }

    /**
     * 将dip转化为px
     *
     * @param dipValue dip值
     */
    private float dip2px(double dipValue) {
        final float scale = this.getResources().getDisplayMetrics().density;
        return (float) (dipValue * scale + 0.5f);
    }

    /**
     * 通过已知坐标后旋转中心坐标以及角度计算旋转后坐标
     */
    private Float[] calculationCoordinate(float x1, float y1, float x0, float y0, float angle) {
        angle = new Float(Math.toRadians(angle));
        float x2 = new Float((x1 - x0) * Math.cos(angle) + (y1 - y0) * Math.sin(angle) + x0);
        float y2 = new Float(-(x1 - x0) * Math.sin(angle) + (y1 - y0) * Math.cos(angle) + y0);
        return new Float[]{x2, y2};
    }
}
